/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package serversidepkg;

import backendpkg.DataSource;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author smag
 */
public class GetOnlineUsers extends HttpServlet {

	
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	try {
        	response.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server
        	response.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance
        	response.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale"
        	response.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility
        	
        	//Get username from session
			HttpSession session = request.getSession();			
            String user = (String) session.getAttribute("username");

            if (user == null) {
               request.setAttribute("Error", "Session has ended.  Please login.");
               RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
               rd.forward(request, response);
            }else{            
	            //Get connection to database
	            DataSource datasource = new DataSource();
	            Connection conn = datasource.getConnection();
	            PreparedStatement statement;
	            
	            //Set last_online date of user that check list of online users
	            //it's useful in order to update presence state of each user
	            String update_date = "UPDATE User "
	                            + "SET last_online=NOW() "
	                            + "WHERE username=?";
				statement = (PreparedStatement) conn.prepareStatement(update_date);
	            statement.setString(1, user);
	            statement.executeUpdate();
	            
	            //Execute query in order to get list of online users
	            //Consider not online users that haven't update last_online from more than 1 minute
	            String query = "SELECT username FROM User "+
	            			   "WHERE username!=? AND last_online IS NOT NULL " +
	            			   "AND TIMEDIFF(NOW(),last_online)<'00:01:00';";
	            statement = (PreparedStatement) conn.prepareStatement(query);
	            statement.setString(1, user);
	            
	            ResultSet result = statement.executeQuery();          
	            
	            //Prepare xml string used to memorize users
	            String xml="<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?><root>";
	
	            while(result.next()){
	                xml+="<online_users><user>" + result.getString("username")+ "</user></online_users>";
	            }
	
	            xml+="</root>";
	            conn.close();
	            response.getWriter().write(xml);
            }
        } catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
